# -*- coding: utf-8 -*-

import datetime
from flask import request, jsonify
from face_recognition import app
from face_recognition.models.face_data import FaceData
from face_recognition.models.face_index import FaceDataIndex
from face_recognition.recognition.image_tools import ImageTools
from face_recognition.service.face_info_service import FaceInfoService
from face_recognition.service.user_info_service import UserInfoService
from face_recognition.utils.array_utils import ListTools
from face_recognition.utils.string_utils import StringUtils
from face_recognition.views.wrapers import wraper_json_data, wraper_need_login


@app.route('/face_recognition/face/truncate/<uid>', methods=['GET'])
@wraper_json_data
@wraper_need_login
def truncate(uid):
	"""
	根据UID清空用户的人脸数据信息
	:param uid:
	:return:
	"""
	if request.method == 'GET':
		if StringUtils.isNotEmpty(uid):
			faceDataService = FaceInfoService()
			if faceDataService.delete_all_with_uid(uid):
				userInfoService = UserInfoService()
				userInfoService.wait_to_collect(uid)
				result = {"status": "success", "message": "数据删除完成！"}
			else:
				result = {"status": "error", "message": "数据删除时发生异常！"}
		else:
			result = {"status": "error", "message": "参数[uid]为空，无法进行数据删除！"}
		return jsonify(result)


@app.route('/face_recognition/collect/<uid>', methods=['POST'])
@wraper_json_data
@wraper_need_login
def collect(uid):
	"""
	收集指定用户的人脸图片base64编码信息，并且进行图片转换，特征提取和保存
	:param uid:
	:return:
	"""
	if request.method == 'POST':
		if StringUtils.isNotEmpty(uid):
			faceDataService = FaceInfoService()
			userInfoService = UserInfoService()
			user = userInfoService.get_with_id(uid)
			if user is not None:
				max_face_count = app.config.get("MAX_FACE_COUNT")
				if user.face_count < max_face_count:
					data = request.get_json()
					if "image_base64" in data.keys() and len(data["image_base64"]) > 0:
						if "file_name" in data.keys() and len(data["file_name"]) > 0:
							# 将base64编码存储到数据库
							face_data_index = FaceDataIndex()
							face_data_index.set_id(str(FaceDataIndex.create_id()))
							face_data_index.file_name = data["file_name"]
							face_data_index.file_status = "NEW"
							face_data_index.user_id = uid
							face_data_index.create_time = datetime.datetime.now()
							
							face_data = FaceData()
							face_data.id = face_data_index.id
							face_data.user_id = uid
							face_data.base64_content = data["image_base64"]
							# 分析人脸特征，存储人脸特征
							feature = ImageTools().get_feature_from_base64(face_data.base64_content)
							if feature is not None:
								# 将特征二维数组转为字符串存储，使用的时候 ，使用eval(feature) 还原为二维数组
								face_data.face_feature = ListTools.ndarray_to_string(feature)
								user, face_data_index, face_data = faceDataService.save(user, face_data_index, face_data)
								result = {"status": "success", "face_count": user.face_count,
								          "max_face_count": max_face_count, "message": "采集成功！"}
							else:
								result = {"status": "error", "message": "未发现人脸信息！"}
						else:
							result = {"status": "error", "message": "未获取图片名称！"}
					else:
						result = {"status": "error", "message": "未获取图片内容！"}
				else:
					result = {"status": "success", "face_count": user.face_count, "max_face_count": max_face_count,
					          "message": "已经满足人像采集数量！"}
			else:
				result = {"status": "error", "message": "用户不存在，UID:" + uid}
		else:
			result = {"status": "error", "message": "参数[uid]为空！"}
		return jsonify(result)


@app.route('/face_recognition/collect_over/<uid>', methods=['GET'])
@wraper_json_data
@wraper_need_login
def collect_over(uid):
	"""
	用户的人脸特征采集完成后，将用户的人脸特征状态修改为待训练： 1
	:param uid:
	:return:
	"""
	if request.method == 'GET':
		# 将该用户的所有人脸信息状态设置为待训练
		userInfoService = UserInfoService()
		userInfoService.collect_over(uid)
		result = {"status": "success", "message": "人脸收集完成！"}
	return jsonify(result)
